package com.ken.app.service.impl;

import com.ken.app.entity.User;
import com.ken.app.mapper.UserRepository;
import com.ken.app.service.UserService;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.util.List;

/**
 * Created by lxg
 * on 2017/2/21.
 */
@Service
public class UserServiceImpl implements UserService {

    @Inject
    private UserRepository userRepository;

    @Inject
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public User findByUsername(String name) {
        Boolean flag = redisTemplate.execute(new RedisCallback<Boolean>() {
            @Override
            public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException {
                RedisSerializer<String> redisSerializer = redisTemplate.getStringSerializer();
                byte[] key = redisSerializer.serialize(name);
                byte[] value = redisSerializer.serialize(name);
                redisSerializer.deserialize(redisConnection.get(key));
                return redisConnection.setNX(key,value);
            }
        });
        return userRepository.findByUsername(name);
    }

    @Override
    public List<User> findAll() {
        return userRepository.findAll();
    }

}
